package com.yuexunit.mobilenurse.module.SignInput.ui;

import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.config.Contracts;
import com.yuexunit.mobilenurse.module.SignInput.adapter.SignTypeAdapter;
import com.yuexunit.mobilenurse.module.SignInput.bean.Sqlite_SignInputBean;
import com.yuexunit.mobilenurse.module.SignInput.model.impl.SignModel;
import com.yuexunit.mobilenurse.module.SignInput.presenter.impl.SignPresenter;
import com.yuexunit.mobilenurse.module.SignInput.ui.view.ISignInput;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sslcjy on 16/1/26.
 */
public class Act_Signs_Input extends KJActivity implements ISignInput {

    @Bind(R.id.types_list)
    public ListView list;
    @Bind(R.id.signinput_bedno)
    public TextView signinput_bedno;
    @Bind(R.id.signinput_name)
    public TextView signinput_name;
    @Bind(R.id.signinput_visitno)
    public TextView signinput_visitno;
    @Bind(R.id.sign_time_day)
    public TextView sign_time_day;
    @Bind(R.id.sign_time_hour)
    public Spinner sign_time_hour;

    private SignPresenter presenter;

    //病人相关信息
    public String inpNo;//住院号
    public String recorder;//记录人员姓名
    public String name;//病人姓名
    public Sqlite_SignInputBean currentbean;//存入数据库的当前病人相关信息
    public String sign_hour;//输入病人的时间
    //体征显示界面的adpater
    private SignTypeAdapter adapter;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_signs_input);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        presenter = new SignPresenter(new SignModel(), this);
        inpNo = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
        recorder = PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGNAME);
        name = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME);
    }


    @Override
    public void initWidget() {
        super.initWidget();
        signinput_name.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME));
        signinput_bedno.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE));
        signinput_visitno.setText(inpNo);
        sign_time_day.setText(StringUtils.getDataTime("yyyy-MM-dd"));
        sign_time_hour.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                sign_hour = (String) parent.getItemAtPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        adapter = new SignTypeAdapter(list, Contracts.signMenuList, R.layout.item_type);
        list.setAdapter(adapter);
    }

    @OnClick(R.id.titlebar_img_back)
    public void out() {
        finish();
    }

    @OnClick({R.id.titlebar_img_menu, R.id.right_text})
    public void uploadMenu() {
        if (adapter != null) {
            if(adapter.getEditBooldValue().size() != 0 || adapter.getEditValue().size() != 0) {
                StringBuilder sbuilder = new StringBuilder();
//            sbuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
//                sbuilder.append("<Body>");
//                sbuilder.append("<Request>");
                Iterator boolditer = adapter.getEditBooldValue().entrySet().iterator();
                String booldValue = "";
                while (boolditer.hasNext()) {
                    Map.Entry entry = (Map.Entry) boolditer.next();
                    int key = (int) entry.getKey();
                    String val = (String) entry.getValue();
                    if (!StringUtils.isEmpty(val)) {
                        booldValue += val;
                        if (boolditer.hasNext()) {
                            booldValue += "/";
                        }
                    }
                }
                if (!StringUtils.isEmpty(booldValue)) {
                    sbuilder.append("<PATIENTS>");
                    sbuilder.append("<INP_NO>" + inpNo + "</INP_NO>");
                    sbuilder.append("<PATIENT_ID></PATIENT_ID>");
                    sbuilder.append("<VISIT_ID></VISIT_ID>");
                    sbuilder.append("<CHECK_DATE>" + StringUtils.getDataTime("yyyy-MM-dd") + "</CHECK_DATE>");
                    if(Integer.valueOf(sign_hour) > 10) {
                        sbuilder.append("<TIME_POINT>6</TIME_POINT>");
                    }
                    else {
                        sbuilder.append("<TIME_POINT>2</TIME_POINT>");
                    }
                    sbuilder.append("<TARGETS>");
                    sbuilder.append("<VITAL_SIGNS>" + Contracts.signMenuList.get(10).getName() + "</VITAL_SIGNS>");
                    sbuilder.append("<VITAL_SIGNS_NO>" + Contracts.signMenuList.get(10).getCode() + "</VITAL_SIGNS_NO>");
                    sbuilder.append("<UNITS>" + Contracts.signMenuList.get(10).getUnit() + "</UNITS>");
                    sbuilder.append("<MAX_VALUE></MAX_VALUE>");
                    sbuilder.append("<MIN_VALUE></MIN_VALUE>");
                    sbuilder.append("<VITAL_SIGNS_VALUE>" + booldValue + "</VITAL_SIGNS_VALUE>");
                    sbuilder.append("<RECORDER>" + recorder + "</RECORDER>");
                    sbuilder.append("</TARGETS>");
                    sbuilder.append("</PATIENTS>");
                }

                Iterator iter = adapter.getEditValue().entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    int key = (int) entry.getKey();
                    String val = (String) entry.getValue();
                    if (!StringUtils.isEmpty(val)) {
                        sbuilder.append("<PATIENTS>");
                        sbuilder.append("<INP_NO>" + inpNo + "</INP_NO>");
                        sbuilder.append("<PATIENT_ID></PATIENT_ID>");
                        sbuilder.append("<VISIT_ID></VISIT_ID>");
                        sbuilder.append("<CHECK_DATE>" + StringUtils.getDataTime("yyyy-MM-dd") + "</CHECK_DATE>");
                        switch (key)
                        {
                            case 0:
                                sbuilder.append("<TIME_POINT>" + sign_hour + "</TIME_POINT>");
                                break;
                            case 1:
                                sbuilder.append("<TIME_POINT>" + sign_hour + "</TIME_POINT>");
                                break;
                            case 2:
                                sbuilder.append("<TIME_POINT>" + sign_hour + "</TIME_POINT>");
                                break;
                            case 3:
                                sbuilder.append("<TIME_POINT>" + sign_hour + "</TIME_POINT>");
                                break;
                            case 4:
                                sbuilder.append("<TIME_POINT>" + sign_hour + "</TIME_POINT>");
                                break;
                            case 5:
                                sbuilder.append("<TIME_POINT>2</TIME_POINT>");
                                break;
                            case 6:
                                sbuilder.append("<TIME_POINT>2</TIME_POINT>");
                                break;
                            case 7:
                                sbuilder.append("<TIME_POINT>2</TIME_POINT>");
                                break;
                            case 8:
                                sbuilder.append("<TIME_POINT>2</TIME_POINT>");
                                break;
                            case 9:
                                sbuilder.append("<TIME_POINT>2</TIME_POINT>");
                                break;
                        }
                        sbuilder.append("<TARGETS>");
                        sbuilder.append("<VITAL_SIGNS>" + Contracts.signMenuList.get(key).getName() + "</VITAL_SIGNS>");
                        sbuilder.append("<VITAL_SIGNS_NO>" + Contracts.signMenuList.get(key).getCode() + "</VITAL_SIGNS_NO>");
                        sbuilder.append("<UNITS>" + Contracts.signMenuList.get(key).getUnit() + "</UNITS>");
                        sbuilder.append("<MAX_VALUE></MAX_VALUE>");
                        sbuilder.append("<MIN_VALUE></MIN_VALUE>");
                        sbuilder.append("<VITAL_SIGNS_VALUE>" + val + "</VITAL_SIGNS_VALUE>");
                        sbuilder.append("<RECORDER>" + recorder + "</RECORDER>");
                        sbuilder.append("</TARGETS>");
                        sbuilder.append("</PATIENTS>");
                    }
                }
//                sbuilder.append("</Request>");
//                sbuilder.append("</Body>");

                Map<String, String> params = new HashMap<>();
                params.put("inpNo", inpNo);
                params.put("timestamp", System.currentTimeMillis() + "");
                params.put("recorder", recorder);
                params.put("signData", sbuilder.toString());
                params.put("timepoint", StringUtils.getDataTime("yyyy-MM-dd") + " " + sign_hour + ":00:00");
                presenter.uploadTypesInfoXML(params, name);
            }
            else {
                ViewInject.toast("未填写任何体征上传信息");
            }

        }else{
            ViewInject.toast("请检查网络连接...");
        }
        finish();
    }

    @Override
    public void uploadSignValue(String buildItem) {
        //buildItem是病人的体征id及体征值
    }

    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
